package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.mapper.ApAssociateWordsMapper;
import com.heima.search.model.Trie;
import com.heima.search.service.ApAssociateWordsService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper , ApAssociateWords> implements ApAssociateWordsService {
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        if (userSearchDto.getSearchWords() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        IPage page = new Page(0 , userSearchDto.getPageSize());
        IPage page1 = page(page, Wrappers.<ApAssociateWords>lambdaQuery().like(ApAssociateWords::getAssociateWords, userSearchDto.getSearchWords()));
        return ResponseResult.okResult(page1.getRecords());
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult searchV2(UserSearchDto userSearchDto) {
        if (userSearchDto.getSearchWords() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String s = redisTemplate.opsForValue().get("associate_list");
        List<ApAssociateWords> apAssociateWords  = null;
        if (StringUtils.isNotEmpty(s)){
            apAssociateWords = JSON.parseArray(s, ApAssociateWords.class);
        }else {
            apAssociateWords = list();
            redisTemplate.opsForValue().set("associate_list" , JSON.toJSONString(apAssociateWords));
        }

        Trie trie = new Trie();
        for (ApAssociateWords apAssociateWord : apAssociateWords) {
            trie.insert(apAssociateWord.getAssociateWords());
        }
        List<String> list = trie.startWith(userSearchDto.getSearchWords());
        List<ApAssociateWords> list1 = new ArrayList<>();
        for (String s1 : list) {
            ApAssociateWords apAssociateWords1 = new ApAssociateWords();
            apAssociateWords1.setAssociateWords(s1);
            list1.add(apAssociateWords1);
        }
        return ResponseResult.okResult(list);
    }


}
